/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package torpedo_server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import torpedo_server.messages.Message;
import torpedo_server.messages.WelcomeMessage;
import torpedo_server.threads.Player1Thread;
import torpedo_server.threads.Player2Thread;

/**
 *
 * @author hengi
 */
public class PlayerHandlerThread extends Thread {
    
    private int listeningPort;
    private ServerSocket ss;
    Socket player1;
    Socket player2;
    
    public static boolean ready1 = false;
    public static boolean ready2 = false;
    
    public static PlayerHandlerThread PlayerHandlerThread = new PlayerHandlerThread(12345);
   
    private PlayerHandlerThread(int listeningPort){
        this.listeningPort=listeningPort;
        try {
            ss = new ServerSocket(listeningPort);
        } catch (IOException ex) {
            Logger.getLogger(PlayerHandlerThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    @Override
    public void run(){
      
       
            try {
                player1= ss.accept();
                //player2= ss.accept();
                //send welcome mess
                SendMess(player1, new WelcomeMessage("Player1"));
                //SendMess(player2, new WelcomeMessage("Player2"));
                Player1Thread p1 = new Player1Thread(player1);
                //Player2Thread p2 = new Player2Thread(player2);
                p1.start();
                //p2.start();
                while(ready1!=true || ready2 != true){
              
                }
                System.out.println("Players are READY");
                // PLAYERS ARE READY LETS PLAY
                
                
                
                
                
            } catch (IOException ex) {
                Logger.getLogger(PlayerHandlerThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            // place the ships
        
        
    }
    
    public void SendMess(Socket s, Message mess) throws IOException{
       OutputStream os = s.getOutputStream();
       ObjectOutputStream oos = new ObjectOutputStream(os);
  
       oos.writeObject(mess);
       oos.flush();
        
       

        
    }
    
}
